package com.luli.Utils;

/**
 * 陆离
 * 2022/11/25 17:35:22
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Paging {
    List<?> list;
    int pageCount;
    public Paging() {

    }

    /**
     * 初始化
     * @param list
     *            数据库查询到的数据集合
     * @param pageCount
     *            每页显示的记录条数
     */
    public Paging(List<?> list, int pageCount) {
        this.list = list;
        this.pageCount = pageCount;
    }

    /**
     * 返回当前页的记录集合
     *
     * @param nowPage
     *            当前页
     * @return 当前页的List集合(页数从0开始)
     */
    @SuppressWarnings("unchecked")
    public List<?> getPagingData(int nowPage) {
        // 总记录条数
        int count = list.size();
        // 分页集合
        List<Object> list = new ArrayList<Object>();
        for (int i = 0; i < count; i += pageCount) {
            List<Object> temp = new ArrayList<Object>();
            if ((count - i) >= pageCount) {
                for (int j = 0; j < pageCount; j++) {
                    temp.add(this.list.get(i + j));
                }
            } else {
                for (int j = 0; j < count - i; j++) {
                    temp.add(this.list.get(i + j));
                }
            }
            list.add(temp);
        }
        // 返回当前页
        return (List<Object>) list.get(nowPage);
    }

    public int getPageNum() {
        // 总记录条数
        int count = list.size();
        // 分页数
        int pageNum = count / pageCount;
        if (count % pageCount != 0) {
            pageNum += 1;
        }
        return pageNum;
    }


    /*
    分页
     */
    public static void main(String[] args) {
        ArrayList<Map<String, Object>> mapArrayList = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name","张三");
        map1.put("age","18");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("name","李四");
        map2.put("age","19");
        Map<String, Object> map3 = new HashMap<>();
        map3.put("name","王五");
        map3.put("age","18");
        Map<String, Object> map4 = new HashMap<>();
        map4.put("name","赵六");
        map4.put("age","20");
        Map<String, Object> map5 = new HashMap<>();
        map5.put("name","孟七");
        map5.put("age","20");
        Map<String, Object> map6 = new HashMap<>();
        map6.put("name","田八");
        map6.put("age","18");
        mapArrayList.add(map1);
        mapArrayList.add(map2);
        mapArrayList.add(map3);
        mapArrayList.add(map4);
        mapArrayList.add(map5);
        mapArrayList.add(map6);
        Paging page1 = new Paging(mapArrayList,2);
        List<Map<String, Object>> paging = (List<Map<String, Object>>)page1.getPagingData(0);
        System.out.print("++++" + page1.getPageNum());
        System.out.println("++++" +page1.pageCount);
        System.out.println("++++" +page1.list);
        System.out.println("++++" +paging);

    }

}
